#include "Button.hpp"

Button::Button(const char *text, SDL_Point pos)
{
    this->setText(text);
    abs_rect.x = pos.x;
    abs_rect.y = pos.y;
    if (text != nullptr)
    {
        TTF_SizeUTF8(this->font == nullptr ? Component::default_font : this->font, this->text, &abs_rect.w, &abs_rect.h);
        abs_rect.w += padding.right + padding.left;
        abs_rect.h += padding.top + padding.bottom;
    }
    else
    {
        abs_rect.w = 100;
        abs_rect.h = 60;
    }
}

Button::~Button()
{
    if (this->text != nullptr)
        delete this->text;
}

void Button::mouseEnter(SDL_MouseMotionEvent &evt)
{
    Component::mouseEnter(evt);
    bk_color = {0x90, 0x90, 0x90, 0xff};
    current_icon = icon_hover;
}

void Button::mouseLeave(SDL_MouseMotionEvent &evt)
{
    Component::mouseLeave(evt);
    bk_color = {0xff, 0xff, 0xff, 0xff};
    current_icon = icon;
}

void Button::mousePress(SDL_MouseButtonEvent &evt)
{
    Component::mousePress(evt);
    bk_color = {0x40, 0x40, 0x40, 0xff};
}

void Button::mouseRelease(SDL_MouseButtonEvent &evt)
{
    Component::mouseRelease(evt);
    bk_color = {0x90, 0x90, 0x90, 0xff};
    current_icon = icon_hover;
}

void Button::mouseClick(SDL_MouseButtonEvent &evt)
{
    Component::mouseClick(evt);
    current_icon = icon_hover;
}

void Button::render(SDL_Renderer *renderer)
{
    if (!visible)
    {
        return;
    }
    SDL_Rect rc;
    memcpy(&rc, &this->abs_rect, sizeof(rc));
    Component::render(renderer);
    if (current_icon.size() > 0)
    {
        Image *img = Resource::getInstance()->getImage(current_icon.c_str());
        SDL_Texture *tex = img->getTexture(renderer);
        SDL_RenderCopy(renderer,tex,nullptr,&abs_rect);
        return;
    }
    SDL_SetRenderDrawColor(renderer, this->bk_color.r, this->bk_color.g, this->bk_color.b, this->bk_color.a);
    SDL_RenderFillRect(renderer, &this->abs_rect);
    int w, h;
    TTF_SizeUTF8(this->font == nullptr ? Component::default_font : this->font, this->text, &w, &h);
    rc.w = w;
    rc.h = h;
    rc.x += (abs_rect.w - w) / 2;
    rc.y += (abs_rect.h - h) / 2;
    if (this->text != nullptr)
    {
        SDL_Surface *sur_text = TTF_RenderUTF8_Blended(this->font == nullptr ? Component::default_font : this->font, this->text, fr_color);
        SDL_Texture *tex_text = SDL_CreateTextureFromSurface(renderer, sur_text);

        SDL_RenderCopy(renderer, tex_text, nullptr, &rc);

        SDL_DestroyTexture(tex_text);
        SDL_FreeSurface(sur_text);
    }

    SDL_SetRenderDrawColor(renderer, this->bd_color.r, this->bd_color.g, this->bd_color.b, this->bd_color.a);
    SDL_RenderDrawRect(renderer, &this->abs_rect);
}

void Button::setText(const char *text)
{
    if (this->text != nullptr)
        delete this->text;
    if (text == nullptr)
    {
        this->text = nullptr;
    }
    else
    {
        this->text = new char[strlen(text) + 1];
        strcpy(this->text, text);
    }
}

const char *Button::getText()
{
    return this->text;
}
